package com.jeesite.modules.sys.wx.fw.utils;

import com.github.sd4324530.fastweixin.api.OauthAPI;
import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import com.github.sd4324530.fastweixin.api.response.OauthGetTokenResponse;
import com.jeesite.common.web.CookieUtils;
import com.jeesite.modules.sys.dao.WxUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Lazy(false)
//@PropertySource("config/fw.properties")
public class FwConfigUtil{

    @Autowired
    private WxUserDao userDao;

    public static String appId;

    public static String secret;




    @Value("${appId}")
    public void setAgentId(String appId) {
        FwConfigUtil.appId = appId;
    }

    @Value("${secret}")
    public void setSecret(String secret) {
        FwConfigUtil.secret = secret;
    }

    public static OauthAPI getOauthAPI() {
        ApiConfig apiConfig = new ApiConfig(FwConfigUtil.appId, FwConfigUtil.secret);
        OauthAPI oauthAPI = new OauthAPI(apiConfig);
        return oauthAPI;
    }

    public static String getOpenId(HttpServletRequest request,HttpServletResponse response) {
        //通过code值获取openid
        OauthAPI oauthAPI = FwConfigUtil.getOauthAPI();

        String code = request.getParameter("code");
        String openId =  CookieUtils.getCookie(request,"openId");
        //为空代表从原地址进来,
        if (StringUtils.isEmpty(openId)) {
            if (StringUtils.isEmpty(code)) {
                openId = request.getParameter("openId");
                if (!StringUtils.isEmpty(openId)) {
                    CookieUtils.setCookie(response, "openId", openId);
                }
            }else{ //不为空说明 重定向 网页授权进来
                OauthGetTokenResponse oauthGetTokenResponse = oauthAPI.getToken(code);
                openId = oauthGetTokenResponse != null ? oauthGetTokenResponse.getOpenid() : "";
                CookieUtils.setCookie(response,"openId",openId);
            }
        }
        return openId;
    }

//    public String findUserByOpenId(String openId) {
//
//        User user =  userDao.findUserByOpenId(openId);
//        String UserId = "";
//
//    }





}